package com.example.skillcinema.adapters

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.example.skillcinema.db.displaymodels.FilmDisplayModel
import com.example.skillcinema.db.repositories.BaseRepository.Companion.FIRST_PAGE

class FilmPagingSource(val getData: suspend (page: Int) -> List<FilmDisplayModel>) :
    PagingSource<Int, FilmDisplayModel>() {
    override fun getRefreshKey(state: PagingState<Int, FilmDisplayModel>): Int? = FIRST_PAGE

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, FilmDisplayModel> {
        val page: Int = params.key ?: FIRST_PAGE
        return runCatching { getData(page) }.fold(onSuccess = {
            LoadResult.Page(
                data = it, prevKey = null, nextKey = if (it.isEmpty()) null else page + 1
            )
        }, onFailure = {
            LoadResult.Error(it)
        })
    }
}